from time import sleep

from appium import webdriver
from appium.webdriver.extensions.android.nativekey import AndroidKey
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By

desired_caps = {
    'platformName': 'Android',  # 被测手机是安卓
    'platformVersion': '12',  # 手机安卓版本
    'deviceName': 'xxx',  # 设备名，安卓手机可以随意填写
    'appPackage': 'cn.com.dfitc.smartinfo',  # 启动APP Package名称
    'appActivity': 'com.dlfc.android.smartinfo.ui.activity.StartActivity',  # 启动Activity名称
    'unicodeKeyboard': True,  # 使用自带输入法，输入中文时填True
    'resetKeyboard': True,  # 执行完程序恢复原来输入法
    'noReset': True,  # 不要重置App
    'newCommandTimeout': 6000,
    'automationName': 'UiAutomator2'
}

# 连接Appium Server，初始化自动化环境
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
# 设置缺省等待时间
driver.implicitly_wait(8)


def to_all():
    driver.find_element(By.ID, 'll_data_report').click()
    sleep(0.5)


def back() -> None:
    driver.press_keycode(AndroidKey.BACK)
    sleep(0.5)


sleep(6)
driver.swipe(800, 800, 300, 800, 1000)
sleep(1)
driver.swipe(800, 800, 300, 800, 1000)
to_all()

list = ['国内期现', '国内期权', '全球指数', '股指期货', '行业分类', '特色下单', '交易下单', '期市要闻', '快讯', '热门专题', '工业品', '贵金属']
for item in list:
    print('当前项目: %s' % item)
    path = "//*[@text='" + item + "']/../../.."
    print(path)

    driver.find_element(By.XPATH, path).click()
    sleep(1)
    back()
    to_all()

list2 = ['现货专区', '主力排名', '实时统计', '生猪指数', '财经早报', '商品专题', '农产品']
for item in list2:
    print('当前项目: %s' % item)
    path = "//*[@text='" + item + "']/../../.."
    print(path)

    driver.find_element(By.XPATH, path).click()
    title = driver.find_element(By.ID, "tv_name_top").text
    assert "现货专区" in title
    sleep(1)
    back()

path1 = "//*[@text='我的消息']/../../.."
driver.swipe(500, 2000, 500, 200, 1000)
try:
    driver.find_element(By.XPATH, path1).click()
    sleep(1)
    back()
except NoSuchElementException:
    driver.swipe(500, 2000, 500, 200, 1000)
    driver.find_element(By.XPATH, path1).click()
    sleep(1)
    back()

input('**** Press to quit..')
driver.quit()


